import React, { useEffect, useState } from 'react';

// const SOCKET_URL = 'ws://192.188.123.2:4399/ws'; 
const SOCKET_URL = 'ws://192.188.123.4:8081/api/websocket/user123';     //fkh

const Test: React.FC = () => {
    const [socket, setSocket] = useState<WebSocket | null>(null);
    const [data, setData] = useState<string>('');
    const [sessionId, setSessionId] = useState<string>('');

    useEffect(() => {
        const ws = new WebSocket(SOCKET_URL);

        ws.onopen = () => {
            console.log('WebSocket 连接已打开');
            setSocket(ws);
        };

        ws.onmessage = (event) => {
            console.log('收到服务器消息:', event.data);
            const response = JSON.parse(event.data);
            if (response.sessionId) {
                setSessionId(response.sessionId); // 保存 sessionId
                console.log('收到 sessionId:', response.sessionId);
            }
        };

        ws.onclose = () => {
            console.log('WebSocket 连接已关闭');
        };

        ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
        };

        return () => {
            ws.close();
        };
    }, []);

    const sendMessage = () => {
        if (socket && socket.readyState === WebSocket.OPEN) {
            const message = {
                sessionId: sessionId,  // 发送 sessionId
                modeType: "start", 
                number:1,            
            };
            socket.send(JSON.stringify("hello from lyx"));
            console.log('发送消息:', message);
        } else {
            console.error('WebSocket 未连接');
        }
    };

    return (
        <div>
            <h1>WebSocket 消息发送</h1>
            <textarea
                value={data}
                onChange={(e) => setData(e.target.value)}
                placeholder="输入消息内容"
            ></textarea>
            <button onClick={sendMessage}>发送消息</button>
        </div>
    );
};

export default Test;
